#include <header.h>

/* Usage:  */

int SendToEveryone(int *size,int fds[],fd_set* cur_set,fd_set*source_set){
    for(int i=0;i<*size;i++)
    {
        int tempFD=fds[i];
        if(FD_ISSET(tempFD,cur_set))
        {
            char buf[100]={0};
            int res_recv=recv(tempFD,buf,sizeof(buf),0);
            ERROR_CHECK(res_recv,-1,"recv");
            if(res_recv==0){
                fds[i]=fds[*size];
                FD_CLR(tempFD,source_set);
                size--;
                i--;
                printf("%d断开连接\n",tempFD);
                continue;

            }
            printf("%d发了消息:%s\n",tempFD,buf);
            for(int j=0;j<*size;j++)
            {
    //            if(i!=j)
    //            {
    //                int res_send=send(fds[j],buf,sizeof(buf),0);
    //                ERROR_CHECK(res_send,-1,"send");
    //            }
            }
        }
    }
    return 1;
}

int main(int argc, char *argv[]){                                  

    char *Port="9031";//监听端口
    char *IP="0.0.0.0";//本机IP

    //创建套接字
    int socketFD=socket(AF_INET,SOCK_STREAM,0);


    struct sockaddr_in socketAddr;
    socketAddr.sin_family=AF_INET;//TCP
    socketAddr.sin_addr.s_addr=inet_addr(IP);//IP
    socketAddr.sin_port=htons(atoi(Port));

    int reuse = 1;
    setsockopt(socketFD, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse));//允许端口重复占用
                                                                          //
    int res_bind =bind(socketFD,(struct sockaddr*)&socketAddr,sizeof(socketAddr));//绑定到套接字
    ERROR_CHECK(res_bind,-1,"bind");                                                                                  

    //监听端口
    listen(socketFD,10);
    // int flag=0;
    // typedef struct connectFD{
    //     int fd;

    // }connect_fd;

    fd_set source_set;
    FD_ZERO(&source_set);
    FD_SET(socketFD,&source_set);

    int fds[1024]={0};//用来记录已建立的连接
    int size=0;//标记已建立的连接数
    while(1){

        fd_set cur_set;
        memcpy(&cur_set, &source_set, sizeof(source_set));
        select(10,&cur_set,NULL,NULL,NULL);
        //如果监听到全连接队列有数据可读，取出放入
        if(FD_ISSET(socketFD,&cur_set)){

            int newfd=accept(socketFD,NULL,NULL);
            fds[size]=newfd;
            FD_SET(newfd,&source_set);
            size++;
            printf("有新链接进来fd=%d\n",newfd);

        }
        SendToEveryone(&size,fds,&cur_set,&source_set);

    }
    close(socketFD);
    return 0;
}
